<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :width="'70%'">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <div class="flex">
        <el-form-item label="开始周" prop="weekDateStart">
          <el-date-picker
            v-model="formData.weekDateStart"
            type="week"
            format="[第] ww [周]"
            value-format="x"
            placeholder="选择开始周"
          />
        </el-form-item>
        <el-form-item label="结束周" prop="weekDateEnd">
          <el-date-picker
            v-model="formData.weekDateEnd"
            type="week"
            format="[第] ww [周]"
            value-format="x"
            placeholder="选择结束周"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="功能室排期" name="roomSchedule">
        <RoomScheduleForm
          ref="roomScheduleFormRef"
          :week-id="formData.id"
          :roomType="formData?.roomType"
        />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { RoomWeeksApi, RoomWeeksVO } from '@/api/school/room/weeks'
import RoomScheduleForm from '../components/RoomScheduleForm.vue'
import dayjs from 'dayjs'
import isoWeek from 'dayjs/plugin/isoWeek'
import isoWeeksInYear from 'dayjs/plugin/isoWeeksInYear'
dayjs.extend(isoWeek)
dayjs.extend(isoWeeksInYear)
/** 功能室周时间 表单 */
defineOptions({ name: 'RoomWeeksForm' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData: any = ref({
  id: undefined,
  roomType: '',
  weekYear: undefined,
  weekDateStart: undefined,
  weekDateEnd: undefined,
  weekNumberStart: undefined,
  weekNumberEnd: undefined,
  startDate: undefined,
  endDate: undefined,
  sort: 1,
  status: 0
})
const formRules = reactive({
  weekYear: [{ required: true, message: '年份不能为空', trigger: 'blur' }],
  weekDateStart: [{ required: true, message: '周日期-开始不能为空', trigger: 'blur' }],
  weekDateEnd: [{ required: true, message: '周日期-结束不能为空', trigger: 'blur' }],
  weekNumberStart: [{ required: true, message: '开始周不能为空', trigger: 'blur' }],
  weekNumberEnd: [{ required: true, message: '结束周不能为空', trigger: 'blur' }],
  startDate: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endDate: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('roomSchedule')
const roomScheduleFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, roomType: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  //赋值功能室类型
  formData.value.roomType = roomType
  console.log(formData.value.roomType, '---formData.value.roomType')

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RoomWeeksApi.getRoomWeeks(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await Promise.all([formRef.value.validate(), roomScheduleFormRef.value.validate()])
  // 提交请求
  formLoading.value = true
  try {
    const data: any = formData.value as unknown as RoomWeeksVO
    //处理周日期信息
    const weekStartInfo = getWeekInfo(data.weekDateStart)
    const weekEndInfo = getWeekInfo(data.weekDateEnd)
    data.weekYear = weekStartInfo.year
    data.weekNumberStart = weekStartInfo.weekNumber
    data.weekNumberEnd = weekEndInfo.weekNumber
    data.startDate = weekStartInfo?.range?.start || null
    data.endDate = weekEndInfo?.range?.end || null
    // 拼接子表的数据
    data.roomSchedules = roomScheduleFormRef.value.getData()
    if (formType.value === 'create') {
      await RoomWeeksApi.createRoomWeeks(data)
      message.success(t('common.createSuccess'))
    } else {
      await RoomWeeksApi.updateRoomWeeks(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    roomType: '',
    weekYear: undefined,
    weekDateStart: undefined,
    weekDateEnd: undefined,
    weekNumberStart: undefined,
    weekNumberEnd: undefined,
    startDate: undefined,
    endDate: undefined,
    sort: 1,
    status: 0
  }
  formRef.value?.resetFields()
}
/** 处理周日期信息 */
function getWeekInfo(date) {
  console.log(date, '选择的周日期---')

  if (!date) return { year: null, weekNumber: null, range: null }

  const d = dayjs(date)
  const weekNumber = d.isoWeek() // 获取 ISO 周序号
  const year = d.isoWeekYear() // 获取 ISO 周对应的年份

  const start = d.startOf('isoWeek').valueOf()
  const end = d.endOf('isoWeek').valueOf()
  //const end = d.endOf('isoWeek').format('YYYY-MM-DD');

  return {
    year,
    weekNumber,
    range: { start, end }
  }
}
</script>
